package com.tianji.promotion.lock;

import com.tianji.common.exceptions.BizIllegalException;
import org.redisson.api.RLock;

public enum MyLockStrategy {

    /**
     * 不等，获取不到锁， 返回false
     * */
    SKIP_FAST(){
        @Override
        public boolean tryLock(RLock lock, DistributeLock prop) throws InterruptedException {
            return lock.tryLock(0, prop.leaseTime(), prop.timeUnit());
        }
    },

    /**
     * 不等，获取不到锁， 抛异常
     * */
    FAIL_FAST(){
        @Override
        public boolean tryLock(RLock lock, DistributeLock prop) throws InterruptedException {
            boolean locked = lock.tryLock(0, prop.leaseTime(), prop.timeUnit());
            if(!locked){
                throw new BizIllegalException("访问太频繁");
            }
            return true;
        }
    },
    /**
     * 做重试，获取不到锁， 返回false
     * */
    SKIP_AFTER_RETRY_TIMEOUT(){
        @Override
        public boolean tryLock(RLock lock, DistributeLock prop) throws InterruptedException {
            return lock.tryLock(prop.waitTime(), prop.leaseTime(), prop.timeUnit());
        }
    },
    /**
     * 做重试，获取不到锁， 抛出异常
     * */
    FAIL_AFTER_RETRY_TIMEOUT(){
        @Override
        public boolean tryLock(RLock lock, DistributeLock prop) throws InterruptedException {
            boolean locked = lock.tryLock(prop.waitTime(), prop.leaseTime(), prop.timeUnit());
            if(!locked){
                throw new BizIllegalException("访问太频繁");
            }
            return true;
        }
    },

    /**
     * 入股获取不到锁，一直不停的阻塞等待
     * */
    KEEP_RETRYING(){
        @Override
        public boolean tryLock(RLock lock, DistributeLock prop) throws InterruptedException {
             lock.lock(prop.leaseTime(), prop.timeUnit());
             return true;
        }
    };

    public abstract boolean tryLock(RLock lock, DistributeLock anno)throws InterruptedException;

}
